#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include "aimage.h"
#include "aimage_utils.h"
#include "aimage_ppm.h"

int main( int argc, const char *argv[] )
{
	const rlim_t kStackSize = 64L * 1024L * 1024L;
	struct rlimit rl;

	int result;
	result = getrlimit( RLIMIT_STACK, &rl );
	if ( result == 0 )
	{
		fprintf( stderr, "Stack size is %dK\n", ((int) ( rl.rlim_cur / 1024L )));
		if ( rl.rlim_cur < kStackSize )
		{
			rl.rlim_cur = kStackSize;
			result = setrlimit( RLIMIT_STACK, &rl );
			if ( result == 0 )
			{
				fprintf( stderr, "Stack size set to %dK\n", ((int) (rl.rlim_cur / 1024L )));
			}
		}
	}

	setrlimit( RLIMIT_STACK, &rl );

#define BLUR_FRAMES 10

	AIMAGE images[ BLUR_FRAMES ];
	AIMAGE alpha_images[ BLUR_FRAMES ];
	AIMAGE image;
	AIMAGE alpha;
	AIMAGE *pimages[ BLUR_FRAMES ];
	AIMAGE *palpha_images[ BLUR_FRAMES ];
	int height, width;

	AIMAGE_PPM_UTILS::load( image, argv[1] );
	image.get_dim( width, height );

	int i;

	for ( i = 0; i < BLUR_FRAMES; ++i )
	{
		images[i].alloc_image( width, height );
		alpha_images[i].alloc_image( width, height );
		AIU::cls( images[i], 0, 0, 0 );
		AIU::cls( alpha_images[i], 1, 1, 1 );
		pimages[ i ] = images+i;
		palpha_images[ i ] = alpha_images+i;
	}
	alpha.alloc_image( width, height );

	if ( argc <= 1 )
	{
		fprintf(stderr, "%s file1 file2...\n", argv[0] );
		exit( 1 );
	}

	for ( i = 1; i < argc + BLUR_FRAMES; ++i )
	{
		int j;

		fprintf(stderr, "Frame %d\n", i );
		
		AIMAGE *swp = pimages[ 0 ];
		AIMAGE *a_swp = palpha_images[ 0 ];

		for ( j = 0; j < BLUR_FRAMES-1; ++j )
		{
			pimages[ j ] = pimages[ j + 1 ];
			palpha_images[ j ] = palpha_images[ j + 1 ];
		}
		pimages[ BLUR_FRAMES - 1 ] = swp;
		palpha_images[ BLUR_FRAMES - 1 ] = a_swp;

		if ( i < argc )
		{
			char aname[ BUFSIZE ];
			AIMAGE_PPM_UTILS::load( *(pimages[ BLUR_FRAMES -1 ]), argv[i] );
			pimages[ BLUR_FRAMES -1 ]->scale_by_256();
			sprintf( aname, "alpha_%s", argv[ i ] );
			AIMAGE_PPM_UTILS::load( *(palpha_images[ BLUR_FRAMES -1 ]), aname );
		}
		else
		{
			AIU::cls( *(pimages[ BLUR_FRAMES -1 ]), 0,0, 0 );
			AIU::cls( *(palpha_images[ BLUR_FRAMES -1 ]), 1,1, 1 );
		}
		AIU::cls( image, 0, 0, 0 );
		AIU::cls( alpha, 0, 0, 0 );

		for ( j = 0; j < BLUR_FRAMES - 1; ++j )
		{
			image.add( *pimages[ j ]);
			alpha.add( *palpha_images[ j ]);
		}
		image.adjust_by_alpha( alpha );

		char filename[ BUFSIZE ];
		sprintf(filename, "blur_%03d.ppm", i+99 );
		AIMAGE_PPM_UTILS::save( image, filename, false );

	}
}

